Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0 

$sites = Get-SPSite -Limit All | Where-Object {$_.CompatibilityLevel -eq "15"}; $sites.Dispose()

function createFolder
{
    param($newFolder)
    Write-Host("Weryfikuję... " + $newFolder)

    # Sprawdzenie, czy folder istnieje. Jeśli nie, to go tworzymy
    if ((test-path $newFolder) -eq $false ) 
    {
        [IO.Directory]::CreateDirectory($newFolder) 
    }
}

function getFiles 
{
    param($libraryUrl)
    $files = $web.GetFolder($libraryUrl)
    $parentTitle = $files.ParentWeb.Title
    $saveLocation = $buFolder + $parentTitle + "\"
    createFolder($saveLocation)

    Write-Host("Przenoszenie " + $parentTitle + " plików")
    
    foreach ($file in $files.Files) 
    {
        #Pobranie pliku
        $binary = $file.OpenBinary()
        $stream = New-Object System.IO.FileStream($saveLocation + $file.Name), Create
        $writer = New-Object System.IO.BinaryWriter($stream)
        $writer.write($binary)
        $writer.Close()
    }
}

$buFolderLocation = "C:\UpgradeDocuments"
$buFolderName = Get-Date -Format yyyyMMdd-HHmmss
$buFolder = $buFolderLocation + "\" + $buFolderName + "\"
createFolder($buFolder)

foreach($site in $sites)
{
    $web = Get-SPWeb -Identity $site.RootWeb.Url
    $listUrl = $site.RootWeb.Url + "/_catalogs/MaintenanceLogs"
    $list = $web.GetList($listUrl)

    #Pobranie plików z głównego korzenia
    # Write-Host($list.ParentWeb.Title)
    getFiles($list.RootFolder.Url)

    #Pobranie plików z biblioteki
    foreach ($folder in $list.Folders) 
    {
        getFiles($folder.Url)
    }
    
    $web.Dispose()
}



